local require = require
local uu     = require("modules.commhm.utils")
local auth   = require("modules.business_common.business_auth")
local config = require("modules.business_common.business_config")
local http   = require("modules.business_common.utils.business_http")

local ngx = ngx
local curr = os.time

local table = table
local pairs = pairs
local ipairs = ipairs
local tonumber = tonumber

local FOO = {
    _VERSION = '0.0.1'
}

local http_request = function( uin, request )
    if not (request and request.cmd) then
        return nil
    end

    request.uin   = uin
    request.json  = 1
    request.time  = curr()
    request.token = auth.make_comm_token(uin, request.time, request.cmd)

    local server = config.get_manor_server_url(uin)
    local response = uu.json2table(http.Get(server, request) or 'nil')
    if response and tonumber(response.ret) == 0 then
        return true, response.data or {}
    end

    -- 失败日志
    http.Log(uu.to_str({ server = server, request = request, response = response }))
    return false
end

FOO.add_item = function (item, reason, uin)
    uin = uin or ngx.ctx.m_params.uin
    return http_request(uin, {
        cmd    = "manor_add_item",
        id     = item.id,
        num    = item.num,
        reason = reason,
    })
end

return FOO